package com.dimples.dd.auth.core.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.dimples.dd.auth.core.model.SysUserDetails;
import com.dimples.dd.common.enums.CommonStatusEnum;
import com.dimples.dd.common.model.DDAuthUser;
import com.dimples.dd.system.api.user.UserFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 系统用户信息加载实现类
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/5/29
 */
@Service
@RequiredArgsConstructor
public class DDUserDetailServiceImpl implements UserDetailsService {

    private final UserFeignClient userFeignClient;

    /**
     * 根据用户名获取用户信息(用户名、密码和角色权限)
     * <p>
     * 用户名、密码用于后续认证，认证成功之后将权限授予用户
     *
     * @param username 用户名
     * @return {@link  UserDetails}
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        DDAuthUser userAuthInfo = userFeignClient.getUserAuthUser(username);

        Assert.isTrue(userAuthInfo != null, "用户不存在");

        assert userAuthInfo != null;
        if (ObjectUtil.notEqual(CommonStatusEnum.ENABLE.getValue(), userAuthInfo.getStatus())) {
            throw new DisabledException("该账户已被禁用!");
        }

        return new SysUserDetails(userAuthInfo);
    }
}















